/*
 * @Author: luoqi
 * @Date: 2022-04-01 15:18:47
 * @LastEditors: luoqi
 * @LastEditTime: 2022-04-27 16:40:35
 * @Description: 
 */
import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Select, Modal, Upload, message, Radio } from 'antd';
import { CheckOutlined, PlusOutlined } from '@ant-design/icons';
import E from 'wangeditor'
import PubSub from 'pubsub-js'
import axios from '../../utils/axios'
import {connect} from 'react-redux'
import {delTab,changeActive} from '../../store/tabAction'

import qs from 'qs'
const { Option } = Select;

const Modifyknowledeg = (props) => {
  const {departmentTree,partTree} = props.types;
  const [inputBlog, setInputBlog] = useState({});
  //数据
  let [data, setData] = useState()
  //表单
  let [form] = Form.useForm()
  //富文本编辑器
  var editor;

  useEffect(() => {
    editor = editor || new E("#content4");
    let config = editor.customConfig ? editor.customConfig : editor.config;
    config.onchange = (html) => {
      setInputBlog({ ...inputBlog, bcontext: html, babstract: editor.txt.text() })
    };
    editor.create();

    //订阅
    let info = PubSub.subscribe('modifyKnowledeg', (_, data) => {
      setData(data)
      console.log(data);
      editor.txt.html(data.content);
    })
    return () => {
      PubSub.unsubscribe(info)
    };
  }, [])

  useEffect(() => {
    form.setFieldsValue({ name: data && data.title, posType:data && data.partPid,depType:data && data.departmentPid,status:data && data.status==true?1:0})
  }, [data])

  const onFinish = (values) => {
    // console.log('Success:', values);
    let { name, depType, posType, status } = values;
    // console.log('内容：', inputBlog.bcontext);
    let index1 = inputBlog.bcontext.indexOf('<img')
    let img = null;
    //获取第一张图片
    if (index1) {
      let str = inputBlog.bcontext.slice(index1)
      let index2 = str.indexOf('"')
      let str2 = str.slice(index2 + 1)
      let index3 = str2.indexOf('"')
      img = str2.slice(0, index3)
    }

    //拼接tag
    let tag = partTree.find(item => item.id == posType).name + ',' + departmentTree.find(item => item.id == depType).name
    // 获取用户id
    let id = JSON.parse(sessionStorage.getItem('userinfo')).id;
    axios({
      url:'/knowledge/upsert',
      method:'post',
      data:qs.stringify({
        id:data.id,
        adminId:data.adminId,
        content:inputBlog.bcontext,
        departmentPid:depType,
        partPid:posType,
        tag:tag,
        title:name,
        status: values.status == 1 ? true : false,
        img: img
      })
    }).then(res=>{
      console.log(res);
      if(res.code==='200'){
        //提示
        message.success('修改成功');
        //删除标签栏
        props.delTab('modifyknowledeg')
        //激活父页面
        props.changeActive('knowledeg')
         //更新父页面
         PubSub.publish('setNumKnowledeg',6)
      }
    })
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  function handleChange(value) {
    console.log(`selected ${value}`);
  }
  return (
    <div>
      <Form
        name="basic"
        form={form}
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="知识名称："
          name="name"
          rules={[{ required: true, message: '请输入疾病知识名称' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
            label="部位一级分类"
            name="posType"
            style={{zIndex:10,position:'relative'}}
          >
            <Select  style={{ width: 120 }} onChange={handleChange}>
              {partTree.map(item=>{
                return <Option key={item.id} value={item.id}>{item.name}</Option>
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="科室一级分类"
            name="depType"
          >
            <Select style={{ width: 120 }} onChange={handleChange}>
            {departmentTree.map(item=>{
                return <Option key={item.id} value={item.id}>{item.name}</Option>
              })}
            </Select>
          </Form.Item>

        <Form.Item
          label="内容"
          
        >
          <div id='content4' style={{zIndex:0,position:'relative'}}></div>
        </Form.Item>
        <Form.Item
          label="状态"
          name="status"
        >
          <Radio.Group  >
            <Radio value={1} >可用</Radio>
            <Radio value={0}>不可用</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          wrapperCol={{
            offset: 12,
            span: 2,
          }}
        >
          <Button type="primary" htmlType='submit' size='large' icon={<CheckOutlined />}>
            提交
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default connect(
  state=>({types:state.types}),
  {delTab,changeActive}
)(Modifyknowledeg);
